package org.xwb.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureDemo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 非阻塞，没有返回值
        CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("没有返回值的");
        });

        // 阻塞，有返回值
        CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("有返回值的");
            return 10;
        }).whenComplete((r,e)->{
            System.out.println("结果是" + r);
        });


        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return 20;
        });
        // 也可以使用 get() 阻塞的方法
        System.out.println(future.get());

        System.out.println("main线程输出");

        // 如果主线程不等待，主线程逻辑执行完就关闭程序了，有可能子线程还没执行忘
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
